#include "types.h"
#include "x86.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "lapic.h"

int
sys_fork(void)
{
  return fork();
}

int
sys_exit(void)
{
  exit();
  return 0;  // not reached
}

int
sys_wait(void)
{
  return wait();
}

int
sys_kill(void)
{
  int pid;

  if(argint(0, &pid) < 0)
    return -1;
  return kill(pid);
}

int
sys_getpid(void)
{
  return myproc()->pid;
}

int
sys_sbrk(void)
{
  int addr;
  int n;

  if(argint(0, &n) < 0)
    return -1;
  addr = myproc()->sz;
  myproc()->sz += n; //只增加sz，不修改内存映射
  return addr;
}

int
sys_sleep(void)
{
  int n;
  uint ticks0;

  if(argint(0, &n) < 0)
    return -1;
  acquire(&tickslock);
  ticks0 = ticks;
  while(ticks - ticks0 < n){
    if(myproc()->killed){
      release(&tickslock);
      return -1;
    }
    sleep(&ticks, &tickslock);
  }
  release(&tickslock);
  return 0;
}

// return how many clock tick interrupts have occurred
// since start.
int
sys_uptime(void)
{
  uint xticks;

  acquire(&tickslock);
  xticks = ticks;
  release(&tickslock);
  return xticks;
}

int
sys_date(void){
  struct rtcdate *r;

  if(argptr(0, (void*)&r, sizeof(*r)) < 0)
    return -1;
  cmostime(r);
  return 0;
}

int
sys_alarm(void)
{
  int ticks;
  void (*handler)(void);

  if(argint(0, &ticks) < 0)
    return -1;
  if(argptr(1, (char**)&handler, 1) < 0)
    return -1;

  struct proc *curproc = myproc();
  curproc->alarmticks = ticks;
  curproc->alarmticks_initial = ticks;
  curproc->alarmhandler = handler;
  curproc->alarmflag = 0;

  //cprintf("sys_alarm: pid=%d, ticks=%d, handler=%p\n", curproc->pid, ticks, handler);  // 调试信息

  return 0;
}


int sys_alarm_save(void) {
  struct proc *curproc = myproc();
  struct trapframe *tf = curproc->tf;

  if (curproc->alarmticks <= 0 || curproc->alarmflag != 1) {
      return -1;
  }
  curproc->alarmflag = 0;

  /* 恢复寄存器 */

  // 取出旧值
  int eip, eax, edx, ecx, ebx, ebp, esi, edi;
  if (argint(-1, &edi) < 0 || argint(0, &esi) < 0 || argint(1, &ebp) < 0 ||
      argint(2, &ebx) < 0 || argint(3, &ecx) < 0 || argint(4, &edx) < 0 ||
      argint(5, &eax) < 0 || argint(6, &eip) < 0) {
      return -1;
  }

  // 赋值
  tf->eip = eip;
  tf->eax = eax;
  tf->edx = edx;
  tf->ecx = ecx;
  tf->ebx = ebx;
  tf->ebp = ebp;
  tf->esi = esi;
  tf->edi = edi;


  // 恢复 ESP
  tf->esp += 0x20;

  return 0;
}